<template>
    <section class="main">
        <input id="toggle-all" class="toggle-all" type="checkbox" />
        <label for="toggle-all" @click="alldata">Mark all as complete</label>
        <ul class="todo-list">
            <!-- These are here just to show the structure of the list items -->
            <!-- List items should get the class `editing` when editing and `completed` when marked as completed -->
            <li :class="{ completed: item.status }" v-for="(item, index) in mainstore.todoList">
                <div class="view">
                    <input class="toggle" type="checkbox" v-model="item.status" @click="put(index)" />
                    <label>{{ item.title }}</label>
                    <button class="destroy" @click="deletes(item.id, index)"></button>
                </div>
                <input class="edit" value="Create a TodoMVC template" />
            </li>
        </ul>
    </section>
</template>
<script lang="ts" setup>
import { nextTick, onMounted, reactive } from 'vue';
//导入axios插件
import axios from 'axios'
//导入store的状态文件
import { assth, useMainStore } from '../store/index'

// 获取状态实例对象
const mainstore = useMainStore()

//设置开关
let ass = reactive({ str: false })
//全选
const alldata = () => {
    if (ass.str == false) {
        //先遍历容器仓库的数据，传入值
        mainstore.todoList.forEach(async (start) => {
            //如果它的值的状态是false的话，就改为true
            if (start.status == false) {
                await axios.put('http://localhost:3004/posts/' + start.id, { title: start.title, status: true })
                //让ring器仓库的状态变为true，就直接自动刷新了
                start.status = true
            }
        })
        ass.str = true
    } else {
        //先遍历容器仓库的数据，传入值
        mainstore.todoList.forEach(async (start) => {
            //如果它的值的状态是true的话，就改为false
            if (start.status == true) {
                await axios.put('http://localhost:3004/posts/' + start.id, { title: start.title, status: false })
                //让ring器仓库的状态变为false，就直接自动刷新了
                start.status = false
            }
        })
    }
}
// 修改状态
const put = async (key: any) => {
    //把它的状态取反之后在传给服务器,再将所有的修改状态过后数据整个传给后端，就是处理过后的最新数据，自然就改掉了
    mainstore.todoList[key].status = !mainstore.todoList[key].status
    let { data } = await axios.put('http://localhost:3004/posts/' + mainstore.todoList[key].id,
        mainstore.todoList[key])
    console.log(data);
}

//删除,根据id来删除服务器数据，利用k来接受index来删除容器仓库的数据
const deletes = async (val: any, k: any) => {
    console.log(k);
    //根据id来删除
    let { data, status } = await axios.delete('http://localhost:3004/posts/' + val)
    if (data && status == 200) {
        mainstore.removedata(k);
    }
}

//页面加载钩子函数，加载数据渲染
onMounted(async () => {
    var { data } = await axios.get('http://localhost:3004/posts')
    // console.log(data);
    //把从服务器获取到的数据存到容器仓库里面
    //模板中可以直接获取到容器仓库的数据，进行循环遍历，js就不用存数据了
    //调用容器仓库的 actions的方法(addtodoList),进行添加到仓库
    mainstore.addtodoList(data);
})

</script>

<style></style>